#!/bin/bash
#
# Copyright (C) 2011 Craig Phillips.  All rights reserved.

prog=$(which $0)
gdmuser="Debian-gdm"
hosts=()
users=()
args="$@"

export DISPLAY=

function usage() {
    cat <<USAGE
Usage: ${0##*/} [options] FILE
Summary:
    Sets a file to be the global system background used by Gnome3 and GDM3.

Options:
    -f --force               Force the use of FILE even if validation fails.
    -u --users USERS         Comma seperated list of users to apply gconf 
                             settings to.
    -g --gdm-user USER       The username of the gdm user.  Default: $gdmuser
    -h --host HOSTNAMES      Comma seperated list of hostnames to apply gconf
                             settings to for each user.

Arguments:
    FILE                     The file to set as the global background.

Copyright:
    Copyright (C) 2011 Craig Phillips.  All rights reserved.

Author:
    Craig Phillips <iwbb.bin@gmail.com>
USAGE
}

[[ ${USER:-$LOGNAME} != "root" ]] && {
    echo >&2 "You should run this as root to avoid authentication prompts"
    sleep 2
}

while [[ $# -gt 0 ]] ; do
    case "$1" in
    (-f|--force)
        force=1
        ;;
    (-h|--host)
        hosts=( "${hosts[@]}" ${2//,/ } )
        shift
        ;;
    (-u|--users)
        users=( "${users[@]}" ${2//,/ } )
        shift
        ;;
    (-g|--gdm-user)
        gdmuser=$2
        shift
        ;;
    (-\?|--help)
        usage
        exit 1
        ;;
    (-*)
        echo >&2 "Unknown option -- $1"
        exit 1
        ;;
    (*)
        break
        ;;
    esac
    shift
done

[[ ${#hosts[@]} -gt 0 ]] && {
    ret=0
    for host in "${hosts[@]}" ; do
        tmpscript=$(mktemp -u /tmp/${0##*/}.XXXXXXX)

        echo "Running at ${USER:-$LOGNAME}@$host"
        ssh $host "cat >$tmpscript ; $tmpscript ${args[@]} ; rm -f $tmpscript" < $prog || {
            ret=$?
            echo >&2 "Failed to update gconf settings on $host for user -- $user"
        }
    done
    exit $ret
}

users=( "${users[@]}" $gdmuser )

file="$(readlink -e "$1" 2>/dev/null)"

[[ ! -f "$file" ]] && {
    echo >&2 "File not found -- ${file:-Not specified}"
    exit 1
}

case "$(file -bi "$file")" in
(image/*) ;;
(*)
    echo >&2 "File is not a supported mime-type -- $file"
    [[ $force -eq 1 ]] || exit 1
    ;;
esac

symlink=/etc/desktop-image
printf "Switching to root to create sym-link:\n    $symlink -> $file\n"
su -c "ln -sf $file $symlink" || {
    echo >&2 "Failed to create sym-link -- $symlink"
    exit 1
}
echo "Symbolic link created: $synlink -> $file"

# Generate script for making gconf adjustments to each user
export script=$(mktemp /tmp/${0##*/}.XXXXXXXX)
trap "rm -f $script" EXIT
chmod 755 $script
echo "Creating temporary script: $script"

awk 'BEGIN { w=0 } /^# GCONF_SETTINGS_SCRIPT/ { w=1; next } (w == 1) { print }' $prog >$script

[[ -s $script ]] || {
    echo >&2 "Failed to create script -- $script"
    exit 1
}

for user in "${users[@]}" ; do
    echo "Updating gconf settings for user: $user"

    [[ -z "$(id -u $user)" ]] && {
        echo >&2 "Invalid user -- $user"
        continue
    }

    su - $user -s /bin/bash -c "$script $symlink" || {
        echo >&2 "Failed to update gconf settings for user -- $user"
    }
done

exit 0

# GCONF_SETTINGS_SCRIPT
#!/bin/bash

echo "Updating settings on $HOSTNAME for ${USER:-$LOGNAME}"

echo "Launching dbus daemon"
$(dbus-launch | sed 's/^/export /g')

[[ -z "$(ps -eao user,command | awk '("'${USER:-$LOGNAME}'" == $1 && $NF ~ /^\/usr\/lib\/d-?conf\/dconf-service/) { print $NF }')" ]] && {
    echo "Starting dconf-service"
    /usr/lib/d*conf/dconf-service &
}

export GSETTINGS_BACKEND=dconf

printf "Updating gconf setting: %s\n    %s = %s\n" "org.gnome.desktop.background"  "picture-uri" "file://$1"
gsettings set org.gnome.desktop.background picture-uri "file://$1"
ret=$?

printf "Verifying gconf setting..."
val=$(gsettings get org.gnome.desktop.background picture-uri)

[[ "$val" != "'file://$1'" ]] && {
    printf >&2 "FAILED\n    Value is: '$val'\n"
    exit 1
}
echo "OK"

exit $ret
